package org.example.web_demo1.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrosFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("CrosFilter filter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 设置允许跨域的域名
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));

        // 设置允许跨域的方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

        // 设置允许跨域的头部
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        // 设置允许携带 Cookie
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 设置预检请求的有效期
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

        // 如果是预检请求，直接返回
        if (httpServletRequest.getMethod().equals("OPTIONS")) {
            return;
        }

        chain.doFilter(request, response);
    }
}
